package com.corner.utils;

import android.provider.MediaStore;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 关于音频的工具类
 *
 * @author Administrator
 */
public class AudioUtil {
    private static final String TAG = "AudioUtil";
    private static String[] mAudiocols = new String[]{
            MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.SIZE, MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.DISPLAY_NAME,
            MediaStore.Audio.Media.BOOKMARK, MediaStore.Audio.Media.ALBUM};

    /**
     * 得到amr的时长
     *
     * @param path
     * @return
     * @throws IOException
     */
    public static long getAmrDuration(String path) throws IOException {
        File file = new File(path);
        long duration = -1;
        int[] packedSize = {12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0,
                0, 0};
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(file, "rw");
            long length = file.length();// 文件的长度
            int pos = 6;// 设置初始位置
            int frameCount = 0;// 初始帧数
            int packedPos = -1;
            // ///////////////////////////////////////////////////
            byte[] datas = new byte[1];// 初始数据值
            while (pos <= length) {
                randomAccessFile.seek(pos);
                if (randomAccessFile.read(datas, 0, 1) != 1) {
                    duration = length > 0 ? ((length - 6) / 650) : 0;
                    break;
                }
                packedPos = (datas[0] >> 3) & 0x0F;
                pos += packedSize[packedPos] + 1;
                frameCount++;
            }
            // ///////////////////////////////////////////////////
            duration += frameCount * 20;// 帧数*20
        } finally {
            if (randomAccessFile != null) {
                randomAccessFile.close();
            }
        }
        return duration;
    }
}
